<template>
  <div class="all">
    <!-- 头部 -->
    <div class="header">
      <a
        href="https://gitee.com/wangtingting-niu/vue3-mm-player"
        target="_blank"
        >在线音乐播放器</a
      >
      <!-- <div class="visitor">visitors <span>0</span></div> -->
      <span class="login">登录</span>
    </div>
    <div class="bottom">
      <div class="main">
        <!-- 左侧 -->
        <div class="left">
          <div class="left-top">
            <button
              @click="goTo('playlist', 1)"
              :class="{ onClick: isActive === 1 }"
            >
              正在播放
            </button>
            <button
              @click="goTo('toplist', 2)"
              :class="{ onClick: isActive === 2 }"
            >
              推荐
            </button>
            <button
              @click="goTo('search', 3)"
              :class="{ onClick: isActive === 3 }"
            >
              搜索
            </button>
            <button
              @click="goTo('userlist', 4)"
              :class="{ onClick: isActive === 4 }"
            >
              我的歌单
            </button>
            <button
              @click="goTo('historylist', 5)"
              :class="{ onClick: isActive === 5 }"
            >
              我听过的
            </button>
          </div>
          <div class="left-bottom">
            <router-view />
          </div>
        </div>
        <!-- 右侧 -->
        <div class="right">
          <div class="right-top">
            <!-- 封面 -->
            <div class="img">
              <img
                v-if="listStore.music.name"
                :src="
                  (listStore.music.album?.artist?.img1v1Url ||
                    listStore.music.al?.picUrl ||
                    listStore.music.image) + '?param=300y300'
                "
                alt=""
              />
              <img v-else src="../../assets/img/player_cover.png" alt="" />
            </div>
            <!-- 信息 -->
            <div>
              <div v-if="listStore.music.name" class="detail-song">
                <span>歌曲名：{{ listStore.music.name }}</span>
                <span
                  >歌手名：{{
                    listStore.music.artists?.[0].name ||
                    listStore.music.ar?.[0]?.name ||
                    listStore.music.singer
                  }}</span
                >
                <span
                  >专辑名：{{
                    listStore.music.album?.name ||
                    listStore.music.al?.name ||
                    listStore.music.album
                  }}</span
                >
              </div>
              <div v-else class="detail-no">
                <span> mmPlayer在线音乐播放器 </span>
                <a href="https://gitee.com/wangtingting-niu/vue3-mm-player">
                  <SvgIcon
                    iconName="icon-github"
                    style="margin-right: 5px"
                  ></SvgIcon>
                  王婷婷
                </a>
              </div>
            </div>
          </div>
          <div class="right-bottom">
            <div ref="musicLyric" class="music-lyric">
              <div class="music-lyric-items" :style="lyricTop">
                <p v-if="!listStore.music.id">还没有播放音乐哦！</p>
                <p v-else-if="nolyric">暂无歌词！</p>
                <template v-else-if="listStore.lyric.length > 0">
                  <p
                    v-for="(item, index) in listStore.lyric"
                    :key="index"
                    :class="{ on: listStore.lyIndex === index }"
                  >
                    {{ item.text }}
                  </p>
                </template>
                <p v-else>歌词加载失败！</p>
              </div>
            </div>
            <!-- <span v-else>还没有播放音乐哦！</span> -->
          </div>
        </div>
      </div>
      <!-- 底部 -->
      <div class="footer">
        <div class="btns">
          <SvgIcon
            iconName="icon-skip-previous2"
            class="prev"
            @click="prevMusic"
            :class="{ hoverCur: listStore.playList.length > 0 }"
          ></SvgIcon>
          <!-- <SvgIcon iconName="icon-play1" class="control"></SvgIcon> -->
          <div>
            <SvgIcon
              v-if="listStore.playing && !listStore.music.id"
              iconName="icon-play_fill"
              class="control"
            ></SvgIcon>
            <SvgIcon
              v-else-if="listStore.playing && listStore.music"
              iconName="icon-play3"
              class="play3"
              @click="play"
              :class="{ hoverCur: listStore.playList.length > 0 }"
            ></SvgIcon>
            <SvgIcon
              v-else
              iconName="icon-pause"
              class="pause"
              @click="pause"
              :class="{ hoverCur: listStore.playList.length > 0 }"
            ></SvgIcon>
          </div>
          <SvgIcon
            iconName="icon-skipnext"
            class="next"
            @click="nextMusic"
            :class="{ hoverCur: listStore.playList.length > 0 }"
          ></SvgIcon>
        </div>
        <div class="music">
          <span v-if="!listStore.music.name" class="noName"
            >欢迎使用mmPlayer在线音乐播放器</span
          >
          <span v-else class="musicName">{{ listStore.music.name }}</span>
          <div class="slider-demo-block">
            <el-slider
              v-model="timeValue"
              :max="listStore.duration"
              :show-tooltip="false"
              @change="changeMusicSlider"
            />
          </div>
        </div>
        <div @click="changeMode">
          <SvgIcon
            v-if="listStore.modeKey === 0"
            iconName="icon-loop"
            class="loop1"
            :class="{ hoverCur: listStore.playList.length > 0 }"
          ></SvgIcon>
          <SvgIcon
            v-if="listStore.modeKey === 1"
            iconName="icon-sequence"
            class="loop"
            :class="{ hoverCur: listStore.playList.length > 0 }"
          ></SvgIcon>
          <SvgIcon
            v-if="listStore.modeKey === 2"
            iconName="icon-random"
            class="loop"
            :class="{ hoverCur: listStore.playList.length > 0 }"
          ></SvgIcon>
          <SvgIcon
            v-if="listStore.modeKey === 3"
            iconName="icon-loop-one"
            class="loop"
            :class="{ hoverCur: listStore.playList.length > 0 }"
          ></SvgIcon>
        </div>
        <SvgIcon
          iconName="icon-message-comments-fill"
          class="filling"
          color="white"
          @click="watchComment"
          :class="{ hoverCur: listStore.playList.length > 0 }"
        ></SvgIcon>

        <div class="volume">
          <SvgIcon
            v-if="listStore.voice"
            iconName="icon-volume-fill"
            class="fill"
            :class="{ hoverCur: listStore.playList.length > 0 }"
            @click="volumeOff"
          ></SvgIcon>
          <SvgIcon
            v-else
            iconName="icon-volume-off"
            class="volume-off"
            :class="{ hoverCur: listStore.playList.length > 0 }"
            @click="volumeOn"
          ></SvgIcon>
          <div class="slider-demo-block">
            <!-- <span class="demonstration">Default value</span> -->
            <el-slider
              v-model="listStore.voice"
              :show-tooltip="false"
              :muted="muted"
              @change="changeVoice"
            />
          </div>
        </div>
      </div>
      <audio
        ref="audio"
        :src="listStore.url"
        @timeupdate="updateCurrentTime"
        @ended="musicEnd"
      ></audio>
    </div>
  </div>
</template>
<script setup>
import { computed, onBeforeUnmount, onMounted, ref, watch } from "vue"
import { useRouter } from "vue-router"
import { useListStore } from "../../store/list"
import { getMusicUrl, getLyric } from "../../api/index"
const listStore = useListStore()
const router = useRouter()
const isActive = ref(0)
const nolyric = ref(false)
const audio = ref()
const timeValue = ref(0) //这是那个进度条的值
const muted = ref(false)

// 关闭声音
const volumeOff = () => {
  listStore.voice = 0
}
// 解除静音
const volumeOn = () => {
  listStore.voice = 50
}
// 上一首歌
const prevMusic = async () => {
  let index =
    listStore.MusicIndex - 1 < 0
      ? listStore.playList.length - 1
      : listStore.MusicIndex - 1
  listStore.setMusicIndex(index)
  let res = await getMusicUrl(listStore.music.id)
  listStore.setUrl(res.data.data[0].url)
  const response = await getLyric(listStore.music.id)
  const tmp = response.data.lrc.lyric
  listStore.setLyric(tmp)
  if (listStore.playing) {
    audio.value.pause()
  } else {
    audio.value.play()
  }
  let duration = listStore.music.duration || listStore.music.dt
  let date = new Date(duration)
  let m = date.getMinutes()
  let s = date.getSeconds()
  let time = `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`
  if (time === "NaN:NaN") {
    time = ""
  }
  listStore.addHistory({
    album:
      listStore.music.album?.name ||
      listStore.music.al?.name ||
      listStore.music.album,
    duration: time || listStore.music.duration,
    id: listStore.music.id,
    image:
      listStore.music.album?.artist?.img1v1Url ||
      listStore.music.al?.picUrl ||
      listStore.music.image,
    name: listStore.music.name,
    singer:
      listStore.music.artists?.[0].name ||
      listStore.music.ar?.[0]?.name ||
      listStore.music.singer,
  })
}
// 下一首歌
const nextMusic = async () => {
  listStore.setMusicIndex(
    (listStore.MusicIndex + 1) % listStore.playList.length
  )
  let res = await getMusicUrl(listStore.music.id)
  listStore.setUrl(res.data.data[0].url)
  const response = await getLyric(listStore.music.id)
  const tmp = response.data.lrc.lyric
  listStore.setLyric(tmp)
  if (listStore.playing) {
    audio.value.pause()
  } else {
    audio.value.play()
  }
  let duration = listStore.music.duration || listStore.music.dt
  let date = new Date(duration)
  let m = date.getMinutes()
  let s = date.getSeconds()
  let time = `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`
  if (time === "NaN:NaN") {
    time = ""
  }
  listStore.addHistory({
    album:
      listStore.music.album?.name ||
      listStore.music.al?.name ||
      listStore.music.album,
    duration: time || listStore.music.duration,
    id: listStore.music.id,
    image:
      listStore.music.album?.artist?.img1v1Url ||
      listStore.music.al?.picUrl ||
      listStore.music.image,
    name: listStore.music.name,
    singer:
      listStore.music.artists?.[0].name ||
      listStore.music.ar?.[0]?.name ||
      listStore.music.singer,
  })
}
// 更换模式
const changeMode = () => {
  listStore.setModeKey()
}
// 产生随机数
const generateRandomInteger = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min + 1)) + min
}
// 音乐播放结束
const musicEnd = async () => {
  if (listStore.modeKey === 0 || listStore.modeKey === 1) {
    listStore.setMusicIndex(listStore.MusicIndex + 1)
  } else if (listStore.modeKey === 2) {
    listStore.setMusicIndex(
      generateRandomInteger(0, listStore.playList.length - 1)
    )
  } else {
    listStore.setMusicIndex(listStore.MusicIndex)
  }
  let res = await getMusicUrl(listStore.music.id)
  listStore.setUrl(res.data.data[0].url)
  const response = await getLyric(listStore.music.id)
  const tmp = response.data.lrc.lyric
  listStore.setLyric(tmp)
  audio.value.play()
  let duration = listStore.music.duration || listStore.music.dt
  let date = new Date(duration)
  let m = date.getMinutes()
  let s = date.getSeconds()
  let time = `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`
  if (time === "NaN:NaN") {
    time = ""
  }
  listStore.addHistory({
    album:
      listStore.music.album?.name ||
      listStore.music.al?.name ||
      listStore.music.album,
    duration: time || listStore.music.duration,
    id: listStore.music.id,
    image:
      listStore.music.album?.artist?.img1v1Url ||
      listStore.music.al?.picUrl ||
      listStore.music.image,
    name: listStore.music.name,
    singer:
      listStore.music.artists?.[0].name ||
      listStore.music.ar?.[0]?.name ||
      listStore.music.singer,
  })
}
// 查看音乐评论
const watchComment = () => {
  router.push(`/comment/${listStore.music.id}`)
}
// 改变音乐进度
const changeMusicSlider = () => {
  audio.value.currentTime = timeValue.value
}
// 调节音量
const changeVoice = () => {
  if (listStore.voice === 0) {
    muted.value = true
  }
  audio.value.volume = listStore.voice / 100
}

watch(
  audio,
  (newval) => {
    listStore.setAudioDom(newval)
  },
  { deep: true }
)
// 歌词滚动样式
let lyricTop = computed(() => {
  return `transform: translateY(${listStore.lyIndex * -46}px)`
})
// 找到当前播放时间对应的歌词
const updateCurrentTime = () => {
  timeValue.value = audio.value.currentTime
  const currentTime = audio.value.currentTime // 当前播放时间
  listStore.lyric.forEach((lyric, index) => {
    if (
      currentTime >= lyric.time &&
      currentTime < (listStore.lyric[index + 1]?.time || Infinity)
    ) {
      listStore.setLyIndex(index) // 更新当前歌词索引
    }
  })
}
// 路由跳转
const goTo = (routePath, num) => {
  isActive.value = num
  router.push("/" + routePath)
}
// 音乐播放
const play = () => {
  listStore.setPlaying()
  audio.value.play()
}
// 音乐暂停
const pause = () => {
  listStore.setPlaying()
  audio.value.pause()
}

onMounted(async () => {
  isActive.value = 1
})

onBeforeUnmount(() => {
  isActive.value = 0
})
</script>
<style scoped lang="less">
.all {
  height: 100%;
  display: flex;
  flex-direction: column;
}
.hoverCur {
  cursor: pointer;
}
.musicName {
  color: #fff;
  font-size: 11px;
  margin-left: -4px;
}
.music-lyric {
  height: 374px;
  width: 310px;
  overflow: hidden;
  text-align: center;
  mask-image: linear-gradient(
    to bottom,
    rgba(255, 255, 255, 0) 0,
    rgba(255, 255, 255, 0.6) 15%,
    rgba(255, 255, 255, 1) 25%,
    rgba(255, 255, 255, 1) 75%,
    rgba(255, 255, 255, 0.6) 85%,
    rgba(255, 255, 255, 0) 100%
  );
  .music-lyric-items {
    text-align: center;
    line-height: 34px;
    font-size: 12px;
    transform: translate3d(0, 0, 0);
    transition: transform 0.6s ease-out;
    color: hsla(0, 0%, 100%, 0.6);
    margin-top: 187px;
  }
}
.play3 {
  width: 25px !important;
  height: 25px !important;
}
.pause {
  width: 40px !important;
  height: 40px !important;
}
::v-deep .el-slider__button-wrapper {
  top: -17px;
}
::v-deep .el-slider__bar {
  height: 2px;
  background-color: #c8cdd2;
  cursor: pointer;
}
.on {
  color: #40ce8f;
}
.detail-song {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: hsla(0, 0%, 100%, 0.6);
  span {
    display: inline-block;
    height: 30px;
    line-height: 30px;
  }
}
.left-bottom {
  overflow: hidden;
  height: 100%;
}
::v-deep .music .el-slider {
  height: 12px;
}
::v-deep .volume .el-slider__runway {
  width: 105px;
}
::v-deep .el-slider__button {
  border: none;
  background-color: #fff;
  height: 10px;
  width: 10px;
}
::v-deep .el-slider__runway {
  height: 2px;
  background-color: hsla(0, 0%, 100%, 0.15);
  width: 100%;
}
.volume {
  margin-left: 20px;
  width: 150px;
  height: 30px;
  display: flex;
  flex-wrap: nowrap;
}
.loop1 {
  width: 25px !important;
  height: 25px !important;
  margin-left: 20px !important;
}
.loop {
  width: 30px !important;
  height: 30px !important;
  margin-left: 15px !important;
}
.filling {
  width: 30px !important;
  height: 30px !important;
  // cursor: pointer;
  margin-left: 20px !important;
}
.fill {
  width: 30px !important;
  height: 30px !important;
  margin-right: 10px !important;
}
.volume-off {
  width: 27px !important;
  height: 27px !important;
  margin-right: 10px !important;
}
.music {
  display: flex;
  flex: 0.95;
  flex-direction: column;
  .noName {
    font-size: 10px;
    color: hsla(0, 0%, 100%, 0.6);
    margin-left: -5px;
  }
}
.right-bottom {
  margin-top: 10px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  overflow: hidden;
  height: 434px;
  width: 310px;
  span {
    font-size: 13px;
    color: hsla(0, 0%, 100%, 0.6);
  }
}

.right-top {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  width: 310px;
  height: 261px;
  padding-bottom: 20px;
  .detail-no {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    span {
      height: 30px;
      line-height: 30px;
      font-size: 14px;
      color: hsla(0, 0%, 100%, 0.6);
    }
    a {
      display: inline-block;
      height: 30px;
      line-height: 30px;
      font-size: 14px;
      color: hsla(0, 0%, 100%, 0.6);
    }
  }
}

.left-top {
  height: 60px;
  .onClick {
    color: #fff;
    border: 1px solid #fff;
  }
  button {
    display: inline-block;
    height: 40px;
    box-sizing: border-box;
    margin-right: 8px;
    padding: 0 23px;
    border: 1px solid hsla(0, 0%, 100%, 0.6);
    color: hsla(0, 0%, 100%, 0.6);
    border-radius: 2px;
    font-size: 14px;
    line-height: 40px;
    overflow: hidden;
    cursor: pointer;
    background-color: transparent;
  }

  button:hover {
    color: #fff;
    border: 1px solid #fff;
  }
}

.footer {
  height: 70px;
  display: flex;
  align-items: center;
  padding: 15px 0 15px 0;
  z-index: 999;
  .btns {
    width: 180px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    .prev {
      width: 36px;
      height: 36px;
    }
    .next {
      width: 36px;
      height: 36px;
    }
    div {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      justify-content: center;
      align-items: center;
      background-color: hsl(0deg 0.95% 56.28% / 30%);
      .control {
        width: 24px;
        height: 24px;
      }
    }
  }

  .music {
    width: 816px;
    margin-left: 40px;
  }
}

.bottom {
  display: flex;
  flex-direction: column;
  margin: 15px 25px 25px 25px;
  min-height: 0;
  flex: 1;
}

.main {
  display: flex;
  height: 711px;
}

.left {
  flex: 3.5;
  display: flex;
  flex-direction: column;
  height: 694px;
}

.right {
  display: flex;
  flex: 1;
  margin-left: 10px;
  flex-direction: column;
  align-items: center;
  .img {
    img {
      width: 186px;
      height: 186px;
    }

    position: relative;
  }

  .img:after {
    content: "";
    position: absolute;
    left: 9px;
    top: 0;
    width: 201px;
    height: 180px;
    background: url("../../assets/img/album_cover_player.png") 0 0 no-repeat;
  }
}

.header {
  height: 60px;
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;

  a {
    color: #fff;
  }

  .login {
    position: absolute;
    right: 10px;
    color: #cdcccc;
    cursor: pointer;
    font-size: 13px;
  }

  .login:hover {
    color: #fff;
  }
}

.visitor {
  border-radius: 3px;
  margin-left: 6px;
  padding: 1px 3px 1px 3px;
  height: 20px;
  color: #fff;
  font-size: 10px;
  background-color: #3b3b3b;
  line-height: 20px;

  span {
    margin-left: 3px;
    color: #fff;
    font-size: 11px;
  }
}
</style>
